<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="企业名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入企业名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="法人名" prop="legalPerson">
        <el-input
          v-model="queryParams.legalPerson"
          placeholder="请输入法人名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="营业执照号码" prop="businessLicenseNumber" label-width="100px">
        <el-input
          v-model="queryParams.businessLicenseNumber"
          placeholder="请输入营业执照号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发证机关" prop="issuingAuthority">
        <el-input
          v-model="queryParams.issuingAuthority"
          placeholder="请输入发证机关"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经营状态" prop="operateStatus">
        <el-select v-model="queryParams.operateStatus" placeholder="请选择经营状态" clearable>
          <el-option
            v-for="dict in dict.type.operateStatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成立时间">
        <el-date-picker
          v-model="daterangeFoundingTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="注册资本" prop="registeredCapital">
        <el-input
          v-model="queryParams.registeredCapital"
          placeholder="请输入注册资本(万元)"
          clearable
          @keyup.enter.native="handleQuery"
          @blur="splitString"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:enterprise:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:enterprise:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:enterprise:remove']"
        >删除
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:enterprise:export']"-->
<!--        >导出-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="enterpriseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="企业id" align="center" prop="id" />-->
      <el-table-column label="企业封面图" align="center" prop="headImg">
        <template slot-scope="scope">
          <imagepreview :src="scope.row.headImg"></imagepreview>
        </template>
      </el-table-column>
      <el-table-column label="企业名" align="center" prop="name" width="150px"/>
      <el-table-column label="法人" align="center" prop="legalPerson"/>
      <el-table-column label="经营范围" align="center" prop="businessBoundaries" :show-overflow-tooltip="true"/>
      <el-table-column label="营业执照号码" align="center" prop="businessLicenseNumber" width="110px"/>
      <el-table-column label="发证机关" align="center" prop="issuingAuthority"/>
      <el-table-column label="经营状态" align="center" prop="operateStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.operateStatus" :value="scope.row.operateStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="成立时间" align="center" prop="foundingTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.foundingTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册资本" align="center" prop="registeredCapital">
        <template slot-scope="scope">
          <span>{{ scope.row.registeredCapital }}</span>(万元)
        </template>
      </el-table-column>
      <el-table-column label="企业介绍" align="center" prop="enterpriseIntroduction" :show-overflow-tooltip="true"/>
      <el-table-column label="企业文化" align="center" prop="corporateCulture" :show-overflow-tooltip="true"/>
      <el-table-column label="荣誉资质图" align="center" prop="honorQualification">
        <template v-slot="scope">
          <el-image :src="scope.row.honorQualification.split(',')[0]"
                    :preview-src-list="scope.row.honorQualification.split(',')"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="telephone" width="110px"/>
      <el-table-column label="邮箱" align="center" prop="email" width="120px" :show-overflow-tooltip="true"/>
      <el-table-column label="网址" align="center" prop="enterpriseUrl" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:enterprise:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:enterprise:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改企业信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">



        <el-form-item label="企业封面图" prop="headImg" label-width="">
          <imageUpload @url="form.headImg=$event" :imgsrc="form.headImg" ></imageUpload>
<!--          <el-input v-model="form.headImg" placeholder="请输入企业封面图"/>-->
        </el-form-item>



        <el-form-item label="企业名" prop="name">
          <el-input v-model="form.name" placeholder="请输入企业名"/>
        </el-form-item>
        <el-form-item label="法人" prop="legalPerson">
          <el-input v-model="form.legalPerson" placeholder="请输入法人"/>
        </el-form-item>
        <el-form-item label="经营范围" prop="businessBoundaries">
          <el-input v-model="form.businessBoundaries" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="营业执照号码" prop="businessLicenseNumber">
          <el-input v-model="form.businessLicenseNumber" placeholder="请输入营业执照号码"/>
        </el-form-item>
        <el-form-item label="发证机关" prop="issuingAuthority">
          <el-input v-model="form.issuingAuthority" placeholder="请输入发证机关"/>
        </el-form-item>
        <el-form-item label="经营状态">
          <el-radio-group v-model="form.operateStatus">
            <el-radio
              v-for="dict in dict.type.operateStatus"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="成立时间" prop="foundingTime">
          <el-date-picker clearable
                          v-model="form.foundingTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择成立时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="注册资本" prop="registeredCapital">
          <el-input v-model="form.registeredCapital" placeholder="请输入注册资本(万元)" type="number" />
        </el-form-item>
        <el-form-item label="企业介绍" prop="enterpriseIntroduction">
          <el-input v-model="form.enterpriseIntroduction" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="企业文化" prop="corporateCulture">
          <el-input v-model="form.corporateCulture" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="荣誉资质图" prop="honorQualification">

          <el-upload
            class="upload-demo"
            :action="urlImgUpload"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :auto-upload=true
            :file-list="fileList"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>

          </el-upload>

<!--          <el-input v-model="form.honorQualification" type="textarea" placeholder="请输入内容"/>-->

        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入电话"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="网址" prop="enterpriseUrl">
          <el-input v-model="form.enterpriseUrl" placeholder="请输入网址"/>
        </el-form-item>

<!--        所属地区级联选择器-->
        <el-form-item label="所属地区" prop="enterpriseUrl">
<!--         v-model="form.enterpriseUrl" -->
<!--          <el-input  placeholder="请输入所属地区"/>-->
<!--            <span class="demonstration">默认 click 触发子菜单</span>-->
            <el-cascader
              v-model="form.regionId"
              :options="areaList"
              :emitPath=false
              ></el-cascader>
        </el-form-item>

<!--        企业类型-->
        <el-form-item label="企业类型" prop="enterpriseUrl">
          <el-select  v-model="form.classifyId" filterable placeholder="请选择">
            <el-option
              v-for="item in classifyName"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">企业产品信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddQyProduct">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteQyProduct">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="qyProductList" :row-class-name="rowQyProductIndex"
                  @selection-change="handleQyProductSelectionChange" ref="qyProduct">
          <el-table-column type="selection" width="50" align="center"/>
<!--          <el-table-column label="序号" align="center" prop="index" width="50"/>-->
          <el-table-column label="图片" prop="productImg" width="150">
            <template slot-scope="scope">
<!--              <el-input v-model="scope.row.productImg" placeholder="请输入图片"/>-->
              <imageUpload @url="scope.row.productImg=$event" :imgsrc="scope.row.productImg" ></imageUpload>

            </template>
          </el-table-column>
          <el-table-column label="产品名" prop="productName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productName" placeholder="请输入产品名"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listEnterprise, getEnterprise, delEnterprise, addEnterprise, updateEnterprise, getAllClassify,getAListOfRegions,queryEnterpriseProduct} from "@/api/system/enterprise";
// import imageUpload from "@/components/imageUpload";
import imageUpload from "@/components/ImageUpload";
export default {
  name: "Enterprise",
  dicts: ['operateStatus'],
  components:{
   imageUpload
  }
  ,

  data() {
    return {
      value:null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedQyProduct: [],
      //企业类型
      classifyName:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业信息表格数据
      enterpriseList: [],
      // 企业产品表格数据
      qyProductList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 产品名时间范围
      daterangeFoundingTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        headImg: null,
        name: null,
        legalPerson: null,
        businessBoundaries: null,
        businessLicenseNumber: null,
        issuingAuthority: null,
        operateStatus: null,
        foundingTime: null,
        registeredCapital: null,
        enterpriseIntroduction: null,
        corporateCulture: null,
        honorQualification: null,
        telephone: null,
        email: null,
        enterpriseUrl: null,

      },
      // 表单参数
      form: {},
      urlImgUpload:'', //上传图片路径
      imgList:[], //图片地址
      fileList: [], //修改时展示图片
      areaList:[], //地区总列表



      // 表单校验
      rules: {
        headImg: [
          {required: true, message: "企业封面图不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "企业名不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.urlImgUpload = process.env.VUE_APP_BASE_API + '/upload'
    //获取所有的地区
    getAListOfRegions().then(res=>{
      // console.log(res)
      let areaListChildrenSjz = []
      let areaListChildrenBd = []
      let areaListChildrenHd = []
      let areaListChildrenXt = []
      let areaListChildrenLf = []
      let areaListChildrenHs = []
      let areaListChildrenCz = []
      let areaListChildrenTs = []
      let areaListChildrenCd = []
      let areaListChildrenZjk = []
      let areaListChildrenQhd = []
      res.data.map((item,index)=>{
          //把市筛选出来
          switch (item.regionOldId){
            case 0:
              this.areaList.push({
                value:item.regionId,
                label:item.regionName,
                children:[]
              })
              break;
          }
        //把县筛选出来
        switch (item.regionOldId){
          case 1:
            areaListChildrenSjz.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
          case 153:
            areaListChildrenBd.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
          case 84:
            areaListChildrenCz.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
          case 115:
            areaListChildrenCd.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
          case 23:
            areaListChildrenHd.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
          case 72:
            areaListChildrenHs.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
          case 61:
            areaListChildrenLf.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
          case 145:
            areaListChildrenQhd.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
          case 100:
            areaListChildrenTs.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
          case 42:
            areaListChildrenXt.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
          case 128:
            areaListChildrenZjk.push({
              value:item.regionId,
              label:item.regionName,
            })
            break
        }

      })
      //将每个市的下属县添加进来
      this.areaList.map((item,index)=>{
          switch (item.value){
            case 1:
              this.areaList[index].children = areaListChildrenSjz
              break
            case 153:
              this.areaList[index].children = areaListChildrenBd
              break
            case 84:
              this.areaList[index].children = areaListChildrenCz
              break
            case 115:
              this.areaList[index].children = areaListChildrenCd
              break
            case 23:
              this.areaList[index].children = areaListChildrenHd
              break
            case 72:
              this.areaList[index].children = areaListChildrenHs
              break
            case 61:
              this.areaList[index].children = areaListChildrenLf
              break
            case 145:
              this.areaList[index].children = areaListChildrenQhd
              break
            case 100:
              this.areaList[index].children = areaListChildrenTs
              break
            case 42:
              this.areaList[index].children = areaListChildrenXt
              break
            case 128:
              this.areaList[index].children = areaListChildrenZjk
              break
          }
      })
      // console.log(areaListChildrenSjz)
      console.log(this.areaList)

    })
    console.log(this.areaList)
    //获取所有的分类
    getAllClassify().then(res=>{
      res.data.map(item=>{
        console.log(res)
        this.classifyName.push(
          {
            value:item.classifyId,
            label:item.classifyName
          }
        )
      })
    })
  },
  methods: {

    splitString(){
      if (this.queryParams.registeredCapital){
        if (this.queryParams.registeredCapital.indexOf("W") == -1) {
          this.queryParams.registeredCapital = this.queryParams.registeredCapital + "W"
        }
      }
    },

    //获取所有分类信息


    //on-change 上传荣誉资质时间
    handleSuccess(res,file,fileList){
      const that = this
      // console.log(res,file,fileList)
      if (fileList.length == 1){
        that.imgList = []
      }

      that.imgList.push(res.file)
      this.form.honorQualification  = that.imgList.join(',')
      console.log(that.imgList)
      console.log(this.queryParams.honorQualification)
      // this.queryParams.honorQualification
    },

    //el上传组件的方法
    handleRemove(file, fileList) {
      console.log(file, fileList);
      console.log(this.fileList);
      //判断删除的哪一个
      if (file.response || file.name){
        this.imgList.map((item,index)=>{

          if (file.response){

          if (item == file.response.file){
            this.imgList.splice(index,1)
            console.log(this.imgList)
          }

          }else if (file.name){

            this.imgList.splice(index,1)
            console.log(this.imgList)

          }
        })
      }
      //每次删除将图片保存
      this.form.honorQualification  = this.imgList.join(',')
      console.log(this.form.honorQualification)

    },
    /** 查询企业信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeFoundingTime && '' != this.daterangeFoundingTime) {
        this.queryParams.params["beginFoundingTime"] = this.daterangeFoundingTime[0];
        this.queryParams.params["endFoundingTime"] = this.daterangeFoundingTime[1];
      }
      listEnterprise(this.queryParams).then(response => {
        this.enterpriseList = response.rows;
        this.total = response.total;
        this.loading = false;
        // console.log(this.enterpriseList)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        headImg: null,
        name: null,
        regionId:null,
        classifyId:null,
        legalPerson: null,
        businessBoundaries: null,
        businessLicenseNumber: null,
        issuingAuthority: null,
        operateStatus: 0,
        foundingTime: null,
        registeredCapital: null,
        enterpriseIntroduction: null,
        corporateCulture: null,
        honorQualification: null,
        telephone: null,
        email: null,
        enterpriseUrl: null,
        createTime: null,
        delFlag: null
      };
      this.qyProductList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.registeredCapital){
        this.queryParams.registeredCapital =  this.queryParams.registeredCapital.slice(0,this.queryParams.registeredCapital.length-1)
      }
      this.getList();

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeFoundingTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业信息";
      this.imgList = []
      this.form.regionId = null
      // getAListOfRegions().then(res=>{
      //   console.log(res)
      //   this.areaList = res.data.map(item=>{
      //     return{
      //       value:item.regionId,
      //       label:item.regionName,
      //       children:[],
      //     }
      //   })
      // })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      this.reset();
      const id = row.id || this.ids
      getEnterprise(id).then(response => {
        this.form = response.data;
        console.log(this.form)
        //获取图片
        let rongyuList = this.form.honorQualification.split(',')
        if (rongyuList.length != 0){
          this.fileList = rongyuList.map(item => {
            this.imgList.push(item)
            return {
              name: item,
              url: item
            }
          });
        }
        this.qyProductList = response.data.qyProductList;
        this.open = true;
        this.title = "修改企业信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        //将级联选择器的地区Id 进行处理
        console.log(this.form.regionId)
        if (Array.isArray(this.form.regionId)){
          this.form.regionId.splice(0,1)
          this.form.regionId = this.form.regionId.toString()
        }

        if (valid) {
          this.form.qyProductList = this.qyProductList;
          if (this.form.id != null) {
            updateEnterprise(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              // this.form.regionId = null
            });
          } else {
            addEnterprise(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // this.form.regionId = null
            });
          }
          //初始化图片链接
          this.imgList=[]
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除企业信息编号为"' + ids + '"的数据项？').then(function () {
        return delEnterprise(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 企业产品序号 */
    rowQyProductIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 企业产品添加按钮操作 */
    handleAddQyProduct() {
      let obj = {};
      obj.productImg = "";
      obj.productName = "";
      this.qyProductList.push(obj);
    },
    /** 企业产品删除按钮操作 */
    handleDeleteQyProduct() {
      if (this.checkedQyProduct.length == 0) {
        this.$modal.msgError("请先选择要删除的企业产品数据");
      } else {
        const qyProductList = this.qyProductList;
        const checkedQyProduct = this.checkedQyProduct;
        this.qyProductList = qyProductList.filter(function (item) {
          return checkedQyProduct.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleQyProductSelectionChange(selection) {
      this.checkedQyProduct = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/enterprise/export', {
        ...this.queryParams
      }, `enterprise_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
